package com.zdp.controller.center;

import com.zdp.common.domain.ResultInfo;
import com.zdp.common.util.CookieUtils;
import com.zdp.common.util.JsonUtils;
import com.zdp.common.util.ResultInfoUtil;
import com.zdp.controller.BaseController;
import com.zdp.pojo.Users;
import com.zdp.pojo.bo.center.CenterUserBO;
import com.zdp.pojo.vo.center.UsersVo;
import com.zdp.service.center.CenterUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;

/**
 * @author sesshomaru
 * @date 2021/8/14 18:18
 * 用户信息接口
 */
@RestController
@RequestMapping("userInfo")
public class CenterUserController extends BaseController {

    @Autowired
    private CenterUserService centerUserService;

    @PostMapping("update")
    public ResultInfo update(
            @RequestParam String userId,
            @RequestBody @Valid CenterUserBO centerUserBO,
            BindingResult result,
            HttpServletRequest request, HttpServletResponse response
    ) {
        if (result.hasErrors()) {
            Map<String, String> errorMap = getErrors(result);
            return ResultInfoUtil.buildError(errorMap);
        }

        Users users = centerUserService.updateUserInfo(userId, centerUserBO);

        UsersVo usersVo = conventUsersVo(users);

        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(usersVo), true);

        //TODO  后续要改，增加令牌token，会整合进redis，分布式会话

        return ResultInfoUtil.buildSuccess(usersVo);
    }

    public UsersVo conventUsersVo(Users user){
        UsersVo usersVo = new UsersVo();
        BeanUtils.copyProperties(user, usersVo);
        return usersVo;
    }
}
